package com.yupi.yupicturebackend.manager.websocket.disruptor;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.lmax.disruptor.dsl.Disruptor;
import com.yupi.yupicturebackend.manager.websocket.disruptor.PictureEditEvent;
import com.yupi.yupicturebackend.manager.websocket.disruptor.PictureEditEventWorkHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 定义一个队列的配置类，这样后续生产者就知道该怎么往队列里写入数据
 */
@Configuration
public class PictureEditEventDisruptorConfig {

    @Resource
    private PictureEditEventWorkHandler pictureEditEventWorkHandler;

    /**
     * 其他地方引用时  可以
     *  使用 @Qualifier 指定名称为 "pictureEditEventDisruptor" 的 Bean
     *     @Autowired
     *     @Qualifier("pictureEditEventDisruptor")
     *     private Disruptor<PictureEditEvent> disruptor;
     * @return
     */
    @Bean("pictureEditEventDisruptor") // 增强 Bean 的可识别性、可维护性和灵活性，确保在复杂场景下能够准确引用和管理该 Bean。
    public Disruptor<PictureEditEvent> messageModelRingBuffer() {
        // ringBuffer 的大小
        int bufferSize = 1024 * 256;
        Disruptor<PictureEditEvent> disruptor = new Disruptor<>(
                PictureEditEvent::new,  // 指定放到缓存区里的数据类型
                bufferSize,  // 指定缓存区大小
                ThreadFactoryBuilder.create().setNamePrefix("pictureEditEventDisruptor").build() // 设置线程工厂
        );
        // 设置消费者
        disruptor.handleEventsWithWorkerPool(pictureEditEventWorkHandler);
        // 开启 disruptor
        disruptor.start();
        return disruptor;
    }
}
